package org.springblade.modules.platform.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import org.springblade.modules.platform.dto.*;
import org.springblade.modules.platform.dto.RuleLinkageSendDTO;
import org.springblade.modules.platform.entity.*;
import org.springblade.modules.platform.props.HuatengProperties;
import org.springblade.modules.platform.service.*;
import org.springblade.modules.platform.utils.CronUtils;
import org.springblade.modules.platform.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springblade.core.log.annotation.ApiLog;
import org.springblade.core.tool.api.R;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author SYG
 * @since 2022-08-30
 */
@RestController
@AllArgsConstructor
@Api(value = "", tags = "规则引擎")
@Slf4j
@RequestMapping("/service-huateng-sxdb/ruleLinkageDevice")
public class RuleLinkageDeviceController {
    private final IMeasuringChainInfoService iMeasuringChainInfoService;
    private final IRuleLinkageService iRuleLinkageService;
    private final IDeviceTableService iDeviceTableService;
    private final IProductTypeService productTypeService;
    private final IDeptInfoTableService iDeptInfoTableService;
    private final HuatengProperties huatengProperties;
    private final IMeasuringChainTableService iMeasuringChainTableService;
    private static RestTemplate restTemplate = new RestTemplate();



    @GetMapping("/list")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "规则引擎列表", notes = "传入ruleLinkagePageDTO")
    public R<RuleLinkageListByPageVO> list(RuleLinkagePageDTO ruleLinkagePageDTO) {
        RuleLinkageListByPageVO deviceTableListVO = iRuleLinkageService.selectRuleLinkageList(ruleLinkagePageDTO);
        return R.data(deviceTableListVO);
    }


    @GetMapping(value = "/info/{id}")
    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "获取设备详细信息", notes = "传入id")
    public  R<RuleLinkageVO> getInfo(@PathVariable("id") Integer id) {
        return R.data(iRuleLinkageService.selectRuleLinkageById(id));
    }

    @PostMapping(value = "/install")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "新增", notes = "传入jobId")
    public R add(@RequestBody RuleLinkageDTO ruleLinkageDTO)  {
        if (!CronUtils.isValid(ruleLinkageDTO.getCronExpression())) {
            return R.fail("cron表达式不正确");
        }
        MeasuringChainInfo one = iMeasuringChainInfoService.getOne(Wrappers.<MeasuringChainInfo>query().lambda().eq(MeasuringChainInfo::getMeasuringChainId, ruleLinkageDTO.getRuleLinkageMeasuringDTOS().get(0).getMeasuringId()));
        if(one!=null){
            ruleLinkageDTO.setDeviceId(one.getVacuumPumpId());
        }
        iRuleLinkageService.instartRuleLinkage(ruleLinkageDTO);
        return R.success("成功");
    }

    @PutMapping("/update")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "修改", notes = "传入sysJob")
    public R update(@RequestBody RuleLinkageDTO ruleLinkageDTO) {
        if (!CronUtils.isValid(ruleLinkageDTO.getCronExpression())) {
            return R.fail("cron表达式不正确");
        }
        MeasuringChainInfo one = iMeasuringChainInfoService.getOne(Wrappers.<MeasuringChainInfo>query().lambda().eq(MeasuringChainInfo::getMeasuringChainId, ruleLinkageDTO.getRuleLinkageMeasuringDTOS().get(0).getMeasuringId()));
        if(one!=null){
            ruleLinkageDTO.setDeviceId(one.getVacuumPumpId());
        }
        iRuleLinkageService.updateRuleLinkage(ruleLinkageDTO);
        return R.success("成功");
    }

    @DeleteMapping("/remove/{ids}")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "删除", notes = "传入id")
    public R remove(@PathVariable Integer[] ids) throws Exception{
        iRuleLinkageService.deleteRuleLinkage(ids);
        return R.success("成功");
    }

    @PutMapping("/updateState")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "启用/禁用", notes = "传入ruleLinkageUpdateDTO")
    public R updateIsIssue(@RequestBody RuleLinkageUpdateDTO ruleLinkageUpdateDTO){
        RuleLinkageVO ruleLinkageVO = iRuleLinkageService.selectRuleLinkageById(ruleLinkageUpdateDTO.getId());
        switch (ruleLinkageUpdateDTO.getRuleLinkageState()){
            case TURNON:
                RuleLinkageSendDTO ruleLinkageSendDTO = new RuleLinkageSendDTO();
                BeanUtils.copyProperties(ruleLinkageVO,ruleLinkageSendDTO);
                List<RuleLinkageVO.RuleLinkageMeasuringVO> linkageDevices = ruleLinkageVO.getRuleLinkageMeasuringDTOS();
                if(!CollectionUtils.isEmpty(linkageDevices)){
                    List<RuleLinkageSendDTO.RuleLinkageMeasuringDTO> collect = linkageDevices.stream().map(x -> {
                        RuleLinkageSendDTO.RuleLinkageMeasuringDTO ruleLinkageDeviceDTO = new RuleLinkageSendDTO.RuleLinkageMeasuringDTO();
                        BeanUtils.copyProperties(x, ruleLinkageDeviceDTO);
                        return ruleLinkageDeviceDTO;
                    }).collect(Collectors.toList());
                    ruleLinkageSendDTO.setRuleLinkageMeasuringDTOS(collect);
                }
                ruleLinkageSendDTO.setState(ruleLinkageUpdateDTO.getRuleLinkageState().getCode());
                ruleLinkageSendDTO.setCount(ruleLinkageVO.getDeviceNumber());
                HttpEntity<RuleLinkageSendDTO> httpEntity = new HttpEntity<>(ruleLinkageSendDTO,new HttpHeaders());
                restTemplate.exchange(huatengProperties.getSendRuleLinkage(), HttpMethod.POST, httpEntity, String.class);
                break;
            case CLOSURE:
                MultiValueMap<String, String> multiValueMap = new LinkedMultiValueMap<>();
                multiValueMap.add("id",ruleLinkageUpdateDTO.getId().toString());
                HttpEntity<MultiValueMap<String, String>> httpEntity1 = new HttpEntity<>(multiValueMap,new HttpHeaders());
                restTemplate.exchange(huatengProperties.getCancelRuleLinkage(), HttpMethod.POST, httpEntity1, String.class);
                break;
        }
        iRuleLinkageService.updateRuleLinkage(ruleLinkageUpdateDTO);
        return R.success("成功");
    }

    @ApiLog("产品列表")
    @GetMapping("/productTypeList")
    @ApiOperationSupport(order = 12)
    @ApiOperation(value = "产品列表", notes = "传入productType")
    public R<List<ProductType>> productTypeList() {
        List<ProductType> list = productTypeService.list(new QueryWrapper<ProductType>().lambda()
                .eq(ProductType::getIsDeleted, 0)
                .eq(ProductType::getState, 1));
        return R.data(list);
    }
    @ApiLog("真空泵控制箱下拉框")
    @GetMapping("/getVacuumList")
    @ApiOperationSupport(order = 12)
    @ApiOperation(value = "真空泵控制箱设备下拉框", notes = "传入productType")
    public R<List<DeviceTable>> getDeviceList() {
        List<DeviceTable> list = iDeviceTableService.list(new QueryWrapper<DeviceTable>().lambda()
                .eq(DeviceTable::getIsDeleted, 0)
                .eq(DeviceTable::getProductId, "HT-VACUUM-PUMP"));
        return R.data(list);
    }
    @GetMapping("/measuringList/{deviceId}")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "根据选中的控制箱查看测量链", notes = "设备ID")
    public R<MeasuringChainInfo> measuringList(@PathVariable("deviceId") String deviceId) {
        MeasuringChainInfo one = iMeasuringChainInfoService.getOne(Wrappers.<MeasuringChainInfo>query().lambda().eq(MeasuringChainInfo::getVacuumPumpId, deviceId));
        return R.data(one);
    }




    @GetMapping("/measuringList")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "关联测量链", notes = "传入measuringPageDTO")
    public R<MeasuringPageVO> measuringList(MeasuringPageDTO measuringPageDTO) {
        MeasuringPageVO measuringPageVO = iDeptInfoTableService.selectListBox(measuringPageDTO);
        return R.data(measuringPageVO);
    }
    @ApiLog("测量连下拉框")
    @GetMapping("/getMeasuringChainList")
    @ApiOperationSupport(order = 12)
    @ApiOperation(value = "测量连下拉框", notes = "传入productType")
    public R<List<MeasuringChainTable>> getMeasuringChainTableList() {
        List<MeasuringChainTable> list = iMeasuringChainTableService.list(new QueryWrapper<MeasuringChainTable>().lambda()
                .eq(MeasuringChainTable::getChainCategory, 2)
                .eq(MeasuringChainTable::getIsDeleted, 0));
        return R.data(list);
    }
    @GetMapping("/vacuumList/{id}")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "根据测量连ID查询真空泵", notes = "设备ID")
    public R<List<DeviceTable>> vacuumList(@PathVariable("id") Long id) {
        MeasuringChainInfo one = iMeasuringChainInfoService.getOne(Wrappers.<MeasuringChainInfo>query().lambda().eq(MeasuringChainInfo::getMeasuringChainId, id));
        if(one!=null){
            List<DeviceTable> list = iDeviceTableService.list(new QueryWrapper<DeviceTable>().lambda()
                    .eq(DeviceTable::getIsDeleted, 0)
                    .in(DeviceTable::getDeviceId, one.getVacuumPumpId().split(","))
                    .eq(DeviceTable::getProductId, "HT-VACUUM-PUMP"));
            return R.data(list);
        }
        return null;
    }
}

